﻿// License: The MIT License (MIT) Copyright (c) 2011..2012 Barend Gehrels

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace GrooveSharp
{
    static class TrackInfoCollection
    {
        private static ObservableCollection<TrackInfo> m_collection = new ObservableCollection<TrackInfo>();

        // The next two members compose an "Enumerator". As soon as the collection changes
        // the "TrackIndex" is invalidated and updated later using "CurrentId"
        private static int? m_TrackIndex = null;
        private static int? m_CurrentId = null;

        static TrackInfoCollection()
        {
            m_collection.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChanged);
        }

        public static ObservableCollection<TrackInfo> Collection()
        {
            return m_collection;
        }

        private static void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // Set to null, this forces an update later on,
            // and avoids updating again and again if a number of tracks is added at once.
            m_TrackIndex = null;
        }

        private static void UpdateInternalIndex()
        {
            if (!m_TrackIndex.HasValue)
            {
                if (m_CurrentId.HasValue)
                {
                    // Find it again using the "CurrentId" property
                    int index = 0;
                    foreach (var track in m_collection)
                    {
                        if (track.Id == m_CurrentId.Value)
                        {
                            m_TrackIndex = index;
                            return;
                        }
                        index++;
                    }
                }
                m_TrackIndex = -1;
            }
        }

        private static int TrackIndex()
        {
            UpdateInternalIndex();
            return m_TrackIndex.Value;
        }

        public static bool Empty()
        {
            return m_collection.Count == 0;
        }

        public static bool HasNext()
        {
            return TrackIndex() + 1 < m_collection.Count;
        }

        public static bool HasPrevious()
        {
            return TrackIndex() > 0;
        }

        private static TrackInfo SetPlayingIndex(int index)
        {
            if (index >= 0 && index < m_collection.Count)
            {
                TrackInfo result = m_collection[index];
                m_TrackIndex = index;
                m_CurrentId = result.Id;
                return result;
            }
            return null;
        }

        public static TrackInfo Next()
        {
            return SetPlayingIndex(TrackIndex() + 1);
        }

        public static TrackInfo Previous()
        {
            return SetPlayingIndex(TrackIndex() - 1);
        }

        public static TrackInfo SetPlayingId(int id)
        {
            int index = 0;
            foreach(TrackInfo track in m_collection)
            {
                if (track.Id == id)
                {
                    m_CurrentId = id;
                    m_TrackIndex = index;
                    return track;
                }
                index++;
            }
            // ID not found, should not occur
            throw new Exception(String.Format("ID {0} not found, should not occur", id));
        }

        public static int Id()
        {
            int index = TrackIndex();
            return index >= 0 && index < m_collection.Count ? m_collection[index].Id : 0;
        }

        public static void Add(TrackInfo track)
        {
            if (track.Id < 0)
            {
                int idFromDb = Db.TrackIdFromFileName(track.FileName);
                track.Id = idFromDb > 0 ? idFromDb : GetUniqueNegativeId();
            }

            // Add it (avoiding duplicates)
            if (track.Id < 0
                || ! (from p in m_collection where p.Id == track.Id select p).Any())
            {
                m_collection.Add(track);
            }
        }

        private static int GetUniqueNegativeId()
        {
            // Give track/file an ID of -1,-2,-3,-4 etc
            var fileIds = from p in m_collection where p.Id < 0 select p.Id;
            return (fileIds.Any() ? fileIds.Min() : 0) - 1;
        }

        public static void SetRating(TrackRating tr)
        {
            foreach (TrackInfo li in from p in TrackInfoCollection.Collection() where p.Id == tr.TrackId select p)
            {
                li.Rating = tr.Value;
            }
        }

    }
}
